//

import JWTToken from '../../helpers/jwt'
import {
  logger
} from '../../helpers/logger'

export default {
  actions: {
    loginRequest({
      dispatch
    }, formData) {
      return axios
        .post("/api/login", formData)
        .then(res => {
          return dispatch("loginSuccess", res.data);
        })
    },
    loginSuccess({
      dispatch
    }, tokenResponse) {
      JWTToken.setToken(tokenResponse.token);
      JWTToken.setAuthId(tokenResponse.auth_id);
      return dispatch("setAuthUser");
    },
    logoutRequest({
      commit
    }) {
      return axios
        .post("/api/logout")
        .then(res => {
          JWTToken.removeToken();
          commit("unsetUser");
        })
        .catch(err => {
          logger(err.response);
        });
    },
    refreshToken({
      dispatch
    }) {
      return axios
        .post("/api/token/refresh")
        .then(res => {
          return dispatch('loginSuccess', res.data)
        })
        .catch(err => {
          logger(err.response);
          return dispatch('logoutRequest')
        });
    },

  }
}
